<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="模型KEY" prop="modelKey">
        <el-input
          v-model="queryParams.modelKey"
          placeholder="请输入模型KEY"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模型名称" prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入模型名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
       <el-form-item label="模型分类" prop="modelCategory">
           <el-select
          v-model="queryParams.modelCategory"
          placeholder="模型分类"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in modelCateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="btnCreate"
          v-hasPermi="['flowable:model:add']"
        >新增</el-button>
      </el-col>
      
       <el-col :span="1.5">
        <el-button
        @click="btnImport"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          v-hasPermi="['flowable:model:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="modelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模型KEY" prop="key" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="模型名称" prop="name" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="模型分类" prop="category" :show-overflow-tooltip="true" width="150" >
         <template slot-scope="scope">
              <el-tag prop="category" v-for="(item, index) in modelCateOptions"   v-if="scope.row.category==item.dictValue">{{item.dictLabel}}</el-tag>
         </template>
      </el-table-column>
      <el-table-column label="版本号" prop="version" align="center">
          <template slot-scope="scope"><el-tag>V{{ scope.row.version }}</el-tag></template>
      </el-table-column>
      <el-table-column label="是否发布" prop="deployed" align="center">
          <template slot-scope="scope"><span>{{ scope.row.deployed?'是':'否' }}</span></template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ transformDateFormat('YYYY-mm-dd HH:MM:SS',scope.row.createTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="lastUpdateTime" width="180">
        <template slot-scope="scope">
          <span>{{transformDateFormat('YYYY-mm-dd HH:MM:SS',scope.row.lastUpdateTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
            <el-dropdown>
                <span class="el-dropdown-link">操作<i class="el-icon-arrow-down el-icon--right"></i></span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-hasPermi="['flowable:model:update']"
                      icon="el-icon-edit" 
                                      @click.native="btnUpdate(row)">修改
                    </el-dropdown-item>
                    <el-dropdown-item 
                    v-hasPermi="['flowable:model:saveModelEditor']"
                    icon="el-icon-edit"
                                      divided
                                      @click.native="btnUpdateModel(row)">流程设计
                    </el-dropdown-item>
                    <el-dropdown-item
                    v-hasPermi="['flowable:model:delete']"
                    icon="el-icon-delete" divided
                                      @click.native="btnDelete(row.id,false)">删除
                    </el-dropdown-item>
                    <el-dropdown-item
                    v-hasPermi="['flowable:model:delete']"
                    icon="el-icon-delete" divided
                                      @click.native="btnDelete(row.id,true)">删除包含历史
                    </el-dropdown-item>
                    <el-dropdown-item
                    v-hasPermi="['flowable:model:saveModelEditor']"
                    icon="el-icon-edit" divided
                                      @click.native="btnDeploy(row.id)">部署
                    </el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog title="流程模型" :visible.sync="dialogFormVisible">
        <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="110px">
            <el-form-item label="模型key" prop="key">
                <el-input v-model="form.key"/>
            </el-form-item>
            <el-form-item label="模型名称" prop="name">
                <el-input v-model="form.name"/>
            </el-form-item>
              <el-form-item label="模型类别" prop="category">
                <el-select v-model="form.category" placeholder="模型类别">
                    <el-option
                      v-for="dict in modelCateOptions"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="模型描述" prop="description">
                <el-input v-model="form.description"/>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button icon="el-icon-close" @click="dialogFormVisible = false">取消</el-button>
            <el-button  icon="el-icon-check" type="primary"
                        @click="dialogStatus==='create'?createData():updateData()">确定
            </el-button>
        </div>
    </el-dialog>
    <el-dialog title="流程导入" :visible.sync="dialogImportVisible" width="400px">
        <el-upload
                class="upload-demo"
                drag
                action
                :show-file-list="false"
                :before-upload="beforeUpload"
                :http-request="doImport"
        >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传.bpmn20.xml,.bpmn文件，且不超过512K</div>
        </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { listModel,importModel,deployModel,addModel,updateModel,deleteModel } from "@/api/flowable/model";
 
export default {
  name: "model",
  data() {
    return {
      selectedRecords: [],
      dialogStatus: '',
      dialogFormVisible:false,
      dialogImportVisible:false,
      modelCateOptions:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      modelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelName: undefined
      },
      form: {
          id: undefined,
          key: '',
          name: '',
          category: '',
          description: '',
          tenantId: ''
      },
      rules: {
          key: [{required: true, message: '请输入KEY', trigger: 'change'}],
          name: [{required: true, message: '请输入模型名', trigger: 'change'}]
      }
    };
  },
  created() {
      this.getList();
      this.getDicts("model_cate").then((response) => {
        this.modelCateOptions = response.data;
      });
  
  },
  methods: {
    selectionChange(selectedRecords) {
      this.selectedRecords = selectedRecords
    },
    btnDelete(id, cascade) {
      let ids = id ? [id] : this.selectedRecords.map(record => {
          return record.id
      })
      if (ids.length == 0) {
          this.msgError('请选择要删除的记录')
          return
      }
      
      deleteModel( ids,cascade).then(({msg}) => {
          this.msgSuccess(msg)
          this.getList()
      })
    },
    resetFrom() {
      this.form = {
          id: undefined,
          key: '',
          name: '',
          category: '',
          description: '',
          tenantId: ''
      }
    },
    btnCreate() {
      this.resetFrom()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
          if (valid) {
              addModel( this.form).then(({msg}) => {
                  this.dialogFormVisible = false
                  this.msgSuccess(msg)
                  this.getList()
              })
          }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
          if (valid) {
              updateModel( this.form).then(({msg}) => {
                  this.dialogFormVisible = false
                  this.msgSuccess(msg)
                  this.getList()
              })
          }
      })
    },
    btnUpdate(row) {
      this.form = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
      })
 
    },
    btnUpdateModel(row) {
      this.$router.push({path: '/flowableModelEdit', query: {id: row.id}})
    },
    btnDeploy(id) {
      deployModel( {id}).then(({msg}) => {
          this.msgSuccess(msg)
          this.getList()
      })
    },
    beforeUpload(file) {
      //上传前格式与大小校验
      const fileName = file.name
      const isFileTypeOk = fileName.endsWith('.bpmn20.xml') || fileName.endsWith('.bpmn')
      const isLt512 = file.size / 1024 / 512 < 1;
      if (!isFileTypeOk) {
          this.msgError("上传文件格式不正确");
      }
      if (!isLt512) {
          this.msgError("上传文件大小不能超过512K");
      }
      return isFileTypeOk && isLt512;
    },
    doImport(fileObj) {
      let formData = new FormData();
      formData.set("file", fileObj.file);
      // formData.set("tenantId", this.importTenantId);
      importModel(formData).then(({msg}) => {
          this.dialogImportVisible = false
          this.msgSuccess(msg)
          this.getList();
      })
    },
    btnImport(){
      this.dialogImportVisible = true;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listModel(this.queryParams).then(
        response => {
          this.modelList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    }
  }
};
</script>